import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { LoginDto, LoginUser } from '@/api/login/type'
import { loginApi } from '@/api/login/loginApi'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  // 登录用户信息
  const loginUser = ref<LoginUser>({
    userId: '',
    userName: '',
    accountId: '',
    accountName: '',
    userSysId: '',
    userSysName: '',
    superUser: false,
    tokenName: '',
    token: '',
    secret: '',
    systemId: '',
    supperFlag: '',
    roleId: '',
    roleName: '',
    companyId: '',
    companyName: ''
  })

  const permissions = ref<Array<string>>([]) // 用户权限编码集合 → 判断按钮权限

  // 计算属性：是否已登录
  const isLoggedIn = computed(() => {
    return !!loginUser.value.token
  })

  // 计算属性：是否为超级用户
  const isSuperUser = computed(() => {
    return loginUser.value.superUser || loginUser.value.supperFlag === '1'
  })

  // 设置用户信息
  const setUserInfo = (user: LoginUser) => {
    loginUser.value = user
    // 同步到sessionStorage
    window.sessionStorage.setItem('userPermissions', JSON.stringify(user.permissions || []))
    loginUser.value.permissions = []
    window.sessionStorage.setItem('loginUser', JSON.stringify(loginUser.value))
    window.sessionStorage.setItem(user.tokenName, user.token)
    permissions.value = user.permissions || []
  }

  const setLoginUser = () => {
    loginUser.value = JSON.parse(window.sessionStorage.getItem('loginUser') || '{}')
    permissions.value = JSON.parse(window.sessionStorage.getItem('userPermissions') || '[]')
  }

  // 清除用户信息
  const clearUserInfo = () => {
    // 重置用户信息
    loginUser.value = {
      userId: '',
      userName: '',
      accountId: '',
      accountName: '',
      userSysId: '',
      userSysName: '',
      superUser: false,
      tokenName: '',
      token: '',
      secret: '',
      systemId: '',
      supperFlag: '',
      roleId: '',
      roleName: '',
      companyId: '',
      companyName: ''
    }
    // 清除sessionStorage
    window.sessionStorage.clear()
  }

  // 退出登录
  const logout = async () => {
    try {
      await loginApi.logout()
      clearUserInfo()
    } catch (error) {
      console.error('退出登录接口调用失败:', error)
    }
  }

  return {
    loginUser,
    permissions,
    isLoggedIn,
    isSuperUser,
    setUserInfo,
    setLoginUser,
    logout
  }
})
